package cn.edu.cqupt.cxcy.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.cqupt.cxcy.dto.IndexImpl;
import cn.edu.cqupt.cxcy.mail.Email;
import cn.edu.cqupt.cxcy.util.Tools;
import cn.edu.cqupt.cxcy.util.Validate;

/**
 * 主页-【创业辅导】
 * @author Dancer-mno
 * @date 2015年10月17日
 */
@SuppressWarnings("serial")
public class ResetPassw extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		String email = request.getParameter("name");
		System.out.println(email);
		PrintWriter out = resp.getWriter();
		HttpSession session = request.getSession();
		if(email == null || "".equals(email) ) {
			out.write("账号不能为空");
			out.flush();
			return;
		}
		if(!Validate.checkEmail(email)) {
			out.write("账号只能为邮箱");
			out.flush();
			return;
		}
		if((session.getAttribute("time") != null)) {
			Calendar c = Calendar.getInstance(); 
			long nowMills = c.getTimeInMillis()/1000; 
			long i = Long.valueOf(session.getAttribute("time").toString());
			if((nowMills - i)>60*3) {
				session.removeAttribute("time");
			} else {
				out.write("请" +(3*60-(nowMills - i)) + "秒过后再提交");
				out.flush();
				return;
			}
		} 
		if(new IndexImpl().usernameIsUnique(email)) {
			out.write("不存在此用户名");
			out.flush();
			return;
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		String check = Tools.getRandomString(10);//获取随机字符串
		new IndexImpl().updateCheck( email, check);//存入数据库
		Email.sendCode(check, email);//发送邮件
		Calendar c = Calendar.getInstance(); 
		long nowMills = c.getTimeInMillis()/1000;//现在的时间(单位：毫秒)/1000 =s
		session.setAttribute("time", nowMills);
		out.write((int)nowMills);
		out.flush();
	}

}
